package modes

import (
	"fmt"
	"time"
)

/*
 *描述 : 轮播图管理
 *
 ******************************************/

type Rotation struct {
	Id    int64  `json:"rot_id" xorm:"id"`       //轮播图id
	PId   int64  `json:"rot_pid" xorm:"pid"`     //项目id
	File  string `json:"rot_file" xorm:"file"`   //轮播图
	URL   string `json:"rot_url" xorm:"url"`     //url
	At    int64  `json:"rot_at" xorm:"at"`       //创建时间
	Start int64  `json:"rot_start" xorm:"start"` //状态 0启用 1禁用
}

func (this *Rotation) TableName() string {
	return "rotation"
}
func (this *Rotation) Save() (int64, error) {
	this.At = time.Now().Unix()
	return Db(0).Insert(this)
}

func (this *Rotation) Get() (bool, error) {
	return Db(0).Get(this)
}
func (this *Rotation) delete(where string) (int64, error) {
	return Db(0).Where(where).Delete(this)
}
func (this *Rotation) Del() (int64, error) {
	where := fmt.Sprintf("id =%d", this.Id)
	return this.delete(where)
}
func (this *Rotation) Count(where string) (int64, error) {
	var val Rotation
	return Db(0).Where(where).Count(&val)
}
func (this *Rotation) update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}

func (this *Rotation) IdSet(field string) (int64, error) {
	where := fmt.Sprintf("id =%d", this.Id)
	return this.update(where, field)
}

func (this *Rotation) where(fage, count, page int, where, field string) ([]Rotation, error) {
	list := make([]Rotation, 0)
	var err error
	if field == "" {
		field = "id"
	}
	if 0 == fage { // 从小到大排序
		err = Db(0).Where(where).
			Asc(field).
			Limit(count, page*count).
			Find(&list)
	} else { // 从大到小排序
		err = Db(0).Where(where).
			Desc(field).
			Limit(count, page*count).
			Find(&list)
	}
	return list, err
}
func (this *Rotation) List(val *Pager) error {
	val.TName = this.TableName()
	w := fmt.Sprintf("uid = %d ", this.PId)
	val.Total, _ = this.Count(w)
	list, err := this.where(val.Rules, val.Count, val.Page-1, w, "")
	if err == nil {
		val.List = list
	}
	return err
}

type RotatData struct {
	Rotation `json:"Rot" xorm:"extends"`
	Project  `json:"pro" xorm:"extends"`
}

func (this *RotatData) Lookups(val *Pager) error {
	list := make([]RotatData, 0)
	val.TName = "rotation"
	val.Page--
	var field, sort string
	switch val.Coll {
	case 0:
		field = fmt.Sprintf("%s.at", val.TName) //时间排序
	case 1:
		field = fmt.Sprintf("%s.pid", val.TName) // 项目
	default:
		field = fmt.Sprintf("%s.at", val.TName) // 时间排序
	}
	if 1 == val.Rules {
		sort = fmt.Sprintf("%s asc", field)
	} else {
		sort = fmt.Sprintf("%s desc", field)
	}
	val.Total, _ = Db(0).Table(val.TName).Where(val.ToWhere()).Count(this)
	err := Db(0).Table(val.TName).
		Join("INNER", "project", fmt.Sprintf("%s.pid = project.id", val.TName)).
		Where(val.ToWhere()).
		OrderBy(sort).
		Limit(val.Count, val.Page*val.Count).
		Find(&list)
	if err == nil {
		val.List = list
	}
	return err
}
